<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" :placeholder="$t('table.department_name')" v-model="listQuery.department_name">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" :placeholder="$t('table.department_code')" v-model="listQuery.department_code">
      </el-input>
      <el-select clearable class="filter-item" style="width: 150px" v-model="listQuery.department_type" :placeholder="$t('table.department_type')">
        <el-option v-for="item in departmentTypeOptions" :key="item.key" :label="item.display_name" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">{{$t('table.add')}}</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
      style="width: 100%">
      <el-table-column :label="$t('table.department_name')"  width="200px" >
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag>{{scope.row.department_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column  align="center" :label="$t('table.department_code')" min-width="150px">
        <template slot-scope="scope">
          <span>{{scope.row.department_code}}</span>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('table.department_type')" width="150px" >
        <template slot-scope="scope">
          <el-tag>{{scope.row.department_type | typeFilter}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.department_parentID')" min-width="200px">
        <template slot-scope="scope">
          <span>{{scope.row.parentDepartment.department_name}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" :label="$t('table.actions')"  class-name="small-padding fixed-width" min-width="200px">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="handleDelete(scope.row)">{{$t('table.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('table.department_name')" prop="department_name">
          <el-input v-model="temp.department_name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.department_code')" prop="department_code">
          <el-input v-model="temp.department_code"></el-input>
        </el-form-item>
        <el-form-item :label="$t('table.department_type')" prop="department_type">
          <el-select class="filter-item" v-model="temp.department_type" placeholder="Please select">
            <el-option v-for="item in departmentTypeOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('table.department_parentID')">
          <treeselect 
            :options="departmentParentOptions"  
            :show-count="true" 
            placeholder="请选择" 
          v-model="temp.parentid"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
  </el-dialog>

  </div>
</template>

<script>
import API from '@/utils/backend_api'
import waves from '@/directive/waves'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
const departmentTypeOptions = [
  { key: '0', display_name: '集团' },
  { key: '1', display_name: '一级部门' }
]
const departmenTypeKeyValue = departmentTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'department',
  components: { Treeselect },
  directives: {
    waves
  },
  data() {
    API.department.parents().then(response => {
      console.log(response)
      if (response.data && response.data.length > 0) {
        response.data.map(item => {
          this.departmentParentOptions.push({ id: item.id, label: item.department_name, children: [] })
        })
      }
    })
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        department_name: undefined,
        department_code: undefined,
        department_type: undefined,
        sort: '+id'
      },
      departmentTypeOptions,
      departmentParentOptions: [],
      temp: {
        department_name: '',
        department_code: '',
        department_type: '',
        parentid: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        department_name: [{ required: true, message: 'name is required' }],
        department_code: [{ required: true, message: 'code is required' }],
        department_type: [{ required: true, message: 'type is required' }]
      },
      downloadLoading: false
    }
  },
  filters: {
    typeFilter(type) {
      return departmenTypeKeyValue[type]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      API.department.all(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data
        if (response.headers && response.headers['x-total-count']) {
          this.total = Number(response.headers['x-total-count'])
        }
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        department_name: '',
        department_code: '',
        department_type: '',
        parenid: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          API.department.add(this.temp).then((response) => {
            console.log('add:')
            console.log(response)
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log(tempData)
          // tempData.timestamp = +new Date(tempData.timestamp)
          API.department.update(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.department.del(row.id).then(response => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$notify({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
